package transaction

import (
	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric-protos-go/common"
)

func getTxType(envelope *common.Envelope) (string, error) {
	var typeStr string
	payload := &common.Payload{}
	err := proto.Unmarshal(envelope.Payload, payload)
	if err != nil {
		return "nil", err
	}

	//fmt.Printf("|---> payload\n%#v\n", payload)

	// -------------------- channel header ---------------
	channelHeader := &common.ChannelHeader{}
	err = proto.Unmarshal(payload.Header.ChannelHeader, channelHeader)
	if err != nil {
		return "nil", err
	}
	//fmt.Printf("---> ChannelHeader\n%#v\n", channelHeader)
	switch channelHeader.Type {
	case 1:
		typeStr = "CONFIG"
		break
	case 2:
		typeStr = "CONFIG_UPDATE"
		break
	case 3:
		typeStr = "ENDORSER_TRANSACTION"
		break
	case 4:
		typeStr = "ORDERER_TRANSACTION"
		break
	default:
		typeStr = "unkown"
		break
	}
	//const (
	//HeaderType_MESSAGE              HeaderType = 0
	//HeaderType_CONFIG               HeaderType = 1
	//HeaderType_CONFIG_UPDATE        HeaderType = 2
	//HeaderType_ENDORSER_TRANSACTION HeaderType = 3
	//HeaderType_ORDERER_TRANSACTION  HeaderType = 4
	//HeaderType_DELIVER_SEEK_INFO    HeaderType = 5
	//HeaderType_CHAINCODE_PACKAGE    HeaderType = 6
	//HeaderType_PEER_ADMIN_OPERATION HeaderType = 8
	//HeaderType_TOKEN_TRANSACTION    HeaderType = 9
	//)
	//fmt.Printf("---> ChannelHeader timestamp\n%#v\n", channelHeader.Timestamp.AsTime())

	return typeStr, nil
}
